# coding = utf-8
import MySQLdb
import ConfigParser
from util.logger import process_log
import traceback
__author__ = 'kongchao'


class MysqlTool(object):
    def __init__(self):
        self.db_conf = self.get_db_conf()
        self.db_connect = self.get_mysql_connect()

    def get_db_conf(self):
        config = ConfigParser.ConfigParser()
        with open("conf/sync_baidu.conf","r") as conf_file:
            config.readfp(conf_file)
            db_username = config.get("mysql", "db_username")
            db_password = config.get("mysql", "db_password")
            db_host = config.get("mysql",  "db_host")
            db_port = config.get("mysql", "db_port")
            db_instance = config.get("mysql", "db_instance")

            db_conf = {
                "uid": db_username,
                "pwd": db_password,
                'server': db_host,
                "port": db_port,
                "db": db_instance
            }
            return db_conf

    def get_mysql_connect(self):
        db_conf = self.db_conf
        db = MySQLdb.connect(host=db_conf['server'], user=db_conf['uid'], passwd=db_conf['pwd'], db=db_conf['db'])
        return db

    def fetch_all_dict(self, sql):
        #if not self.db_connect:
        db_connect = self.get_mysql_connect()
        cur = None
        try:
            cur = db_connect.cursor(cursorclass=MySQLdb.cursors.DictCursor)
            cur.execute(sql)
            map = cur.fetchall()
        except Exception,e:
            raise Exception("failed to fetch data")
        finally:
            cur.close()
            if db_connect:
                db_connect.close()
        return map

    def fetch_all_list(self,sql):
        #if not self.db_connect:
        db_connect = self.get_mysql_connect()
        cur = None
        try:
            cur = db_connect.cursor(cursorclass=MySQLdb.cursors.SSCursor)
            cur.execute(sql)
            process_log().debug(sql)
            data = cur.fetchall()
        except Exception, e:
            process_log().warning(traceback.format_exc())
            raise e
        finally:
            cur.close()
            if db_connect:
                db_connect.close()
        return data

    def close_connect(self):
        if self.db_connect:
            self.db_connect.close()



